package com.wxxymaker.utils;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: Soft
 * @Date: 2018/6/30 0:04
 * @Desc: 简单缓存，带本地数据保存
 */
public class SimpleCache implements Runnable {
    private static Map<String, Object> cacheMap;
    private static File  cacheFile = null;
    static {
        cacheFile = new File(Const.CLASSPATH + "cache/simpleCache");
        initCache();
    }

    /**
     * 向缓存中添加数据
     * @param key 键
     * @param val 值
     */
    public static void set(String key, Object val) {
        cacheMap.put(key, val);
        // 异步执行 更新缓存
        new Thread(new SimpleCache()).start();
    }

    /**
     * 根据键从缓存中读取数据
     * @param key 键
     * @return 对应的值
     */
    public static Object get(String key) {
        return cacheMap.get(key);
    }

    /**
     * 清空缓存
     */
    public static void clear() {
        cacheMap.clear();
    }

    /**
     * 清空缓存 但不删除安装锁
     */
    public static void clearNoLock() {
        Object o = cacheMap.get(Const.lockKey);
        Object o1 = cacheMap.get(Const.configKey);
        cacheMap.clear();
        if (o != null) {
            cacheMap.put(Const.lockKey, o);
        }
        if (o1 != null) {
            cacheMap.put(Const.configKey, o1);
        }
    }

    /**
     * 从文件中加载数据
     */
    @SuppressWarnings("unchecked")
    private static void initCache() {
        if (cacheFile.exists()) {
            try {
                ObjectInputStream input = new ObjectInputStream(new FileInputStream(cacheFile));
                cacheMap = (Map<String, Object>) input.readObject();
                input.close();
            } catch (ClassNotFoundException | IOException e) {
                e.printStackTrace();
            }
        } else {
           cacheMap = new ConcurrentHashMap<>();
        }
        cacheMap.put(Const.ipKey, new ArrayList<>());
        if (!cacheMap.containsKey(Const.tempImgKey)) {
            cacheMap.put(Const.tempImgKey, new HashMap<String, List<String>>());
        }
    }

    /**
     * 更新缓存 将内存中的数据保存到文件中
     */
    private static void flushData() {
        if (!cacheMap.isEmpty()) {
            try {
                ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(cacheFile));
                out.writeObject(cacheMap);
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void run() {
        flushData();
    }
}
